<template>
  <div>
    <cus-modal ref="modal" title="编辑" @on-visible-change="onVisibleChange" @onOk="onOk">
      <Form ref="formValidate" :model="form" :rules="ruleValidate" :label-width="80">
        <FormItem label="节点类型" prop="resourceType">
          <RadioGroup v-model="form.resourceType" size="large">
            <Radio :label="1">目录</Radio>
            <Radio :label="2">菜单</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="路由名称" prop="name" :label-width="100">
          <Input v-model="form.name" clearable style="width: 200px" size="large" placeholder="请输入路由名称"></Input>
        </FormItem>
        <FormItem label="上级节点" prop="pid">
          <Poptip trigger="click" title="选择上级节点" content="content" width="240">
            <Input v-model="form.partnerTitle" style="width: 200px" size="large" readonly placeholder="请选择上级节点"></Input>
            <div slot="content">
              <rollTree :id="form.pid"
                        v-if="treeList.length && treeList[0]['children'].length"
                        :treeList="treeList" @onSelectChange="onSelectChange"></rollTree>
            </div>
          </Poptip>
        </FormItem>
        <FormItem label="节点路由" prop="url" :label-width="100">
          <Input v-model="form.url" clearable style="width: 200px" placeholder="请输入节点路由" size="large"></Input>
        </FormItem>
        <FormItem label="文件路径" prop="filePath" v-if="form.resourceType === 2">
          <Select v-model="form.filePath" clearable filterable style="width: 200px" placeholder="请选择文件路径" size="large">
            <Option :value="v.pagePath" v-for="(v,i) in pageList" :key="i">{{v.pagePath}}</Option>
          </Select>
        </FormItem>
        <FormItem label="节点图标" prop="icon">
          <Poptip trigger="click" title="选择节点图标" content="content" width="310">
            <Input v-model="form.icon" size="large" style="width: 200px" :icon="form.icon" readonly placeholder="请选择节点图标"></Input>
            <div slot="content">
              <div class="node-key hide-scrollbar">
                <Button class="node-key-icon" size="large" :icon="v" v-for="(v,i) in iconList" @click="form.icon = v" :key="i"/>
              </div>
            </div>
          </Poptip>
        </FormItem>
        <FormItem label="排序号" prop="seq">
          <InputNumber style="width: 200px" size="large" :min="0" v-model="form.seq"></InputNumber>
        </FormItem>
        <FormItem label="按钮权限" v-if="form.resourceType === 2">
          <Select class="multiple-select" clearable v-model="form.buttonList" multiple style="width:200px" size="large">
            <Option v-for="(item,ind) in btnPermissions" :value="ind" :key="item.buttonId">{{ item.buttonName }}
            </Option>
          </Select>
        </FormItem>
        <div class="flex">
          <Icon type="ios-alert" size="20" style="margin-right: 5px;" color="orange"/>
          菜单修改需刷新页面或重新登录后生效
        </div>
      </Form>
      <Spin size="large" fix v-if="loading"></Spin>
    </cus-modal>
  </div>
</template>

<script>
  import rollTree from "./rollTree";
  import {firstRouter} from '@/router/routers';
  import iconList from '@/config/icons';
  import {pageInfo} from '@/config';
  import {addMenu, getJsonMenuList, getMenuInfo, modifyMenu, addBtnPermissions} from '@/api/business/system';

  const form = {
    id: '',
    resourceType: 1,
    name: '',
    url: '',
    partnerTitle: '',
    pid: null,
    filePath: '',
    icon: '',
    seq: 0,

    buttonList: [],
    tempList: [],
    list: []
  }

  export default {
    components: {rollTree},
    name: "menuModal",
    data() {
      return {
        loading: false,
        pageList: pageInfo,
        iconList: iconList,
        treeList: [],
        form: form,
        ruleValidate: {
          name: [
            {required: true, message: '路由名称不能为空', trigger: 'blur'},
          ],
          url: [
            {required: true, message: '节点路由不能为空', trigger: 'blur'},
          ]
        }
      }
    },
    computed: {
      btnPermissions() {
        let i = this.pageList.filter(val => {
          return val.pagePath === this.form.filePath
        });
        if (i.length) {
          return i[0].btnPermissions;
        } else return [];
      },
      buttonList() {
        return this.btnPermissions.filter((v, ind) => {
          let flag = false;
          for (let i = 0; i < this.form.buttonList.length; i++) {
            if (ind === this.form.buttonList[i]) {
              flag = true;
            }
          }
          return flag;
        });
      },
      buttonLists(){
        let moreList = [];
        this.form.buttonList.forEach(v => {
          let flag = true;
          this.form.tempList.forEach(val => {
            if (v == val) flag = false;
          })

          if (flag) moreList.push(v);
        })
        return this.btnPermissions.filter((v, ind) => {
          let flag = false;
          for (let i = 0; i < moreList.length; i++) {
            if (ind === moreList[i]) {
              flag = true;
            }
          }
          return flag;
        })
      },
      deleteButtonList(){
        let deleteList = [];
        let tempList = [];
        this.form.tempList.forEach(v => {
          let flag = true;
          this.form.buttonList.forEach(val => {
            if (v == val) flag = false;
          })

          if (flag) deleteList.push(v);
        })

        this.btnPermissions.forEach((v, ind) => {
          let flag = false;
          for (let i = 0; i < deleteList.length; i++) {
            if (ind === deleteList[i]) {
              flag = true;
            }
          }
          if (flag) tempList.push(v.buttonId);
        });

        let intId = this.form.list.filter((v) => {
          let flag = false;
          for (let i = 0; i < tempList.length; i++) {
            if (v.buttonId === tempList[i]) {
              flag = true;
            }
          }
          return flag;
        })
        return intId.map(v => v.id)
      }
    },
    mounted() {
      this.form = this.$cu.deepClone(form);
    },
    methods: {
      onVisibleChange(v) {
        this.$refs['formValidate'].resetFields();
        if (!v) this.form = this.$cu.deepClone(form);
      },
      show() {
        this.loading = false;
        this.$refs['modal'].show = true;
        let task = [];
        if (this.form.id) {
          this.loading = true;
          task.push(this.getMenuInfoApi())
        }
        Promise.all(task).then(() => {
          this.getJsonMenuListApi().then(() => this.loading = false);
        });
      },
      onSelectChange({id, title}) {
        this.form.pid = id;
        this.form.partnerTitle = title;
      },
      onOk() {
        this.$refs['formValidate'].validate(valid => {
          if (valid) {
            this.loading = true;
            if (this.form.id) {
              this.modifyMenuApi();
            } else this.addMenuApi();
          }
        })
      },
      onSuccess(msg) {
        this.loading = false;
        this.$Message.success(msg);
        this.$refs['modal'].show = false;
        this.$parent.onInit();
      },
      // 获取树状图数据
      getJsonMenuListApi() {
        return new Promise(resolve => {
          getJsonMenuList({}).then(res => {
            if (res.code === 1) {
              this.treeList = [];
              let routers = JSON.parse(JSON.stringify(firstRouter))
              // routers[0].children = JSON.parse(JSON.stringify(res.data));
              let filterArr = JSON.parse(JSON.stringify(res.data)).filter(item => item.type == 6);
              routers[0].children = filterArr;
              let node = this.$cu.dealTree(this.$cu.deepClone(routers), node => node.id == this.form.pid);
              console.log(node);
              if (node.length) {
                this.form.partnerTitle = node[0]['name'];
              }
              this.$nextTick(() => {
                this.treeList = routers;
              })
              resolve();
            }
          })
        })
      },
      // 获取菜单详情
      getMenuInfoApi() {
        return new Promise(resolve => {
          getMenuInfo({id: this.form.id}).then(res => {
            if (res.code === 1) {
              this.form.filePath = res.data.base.filePath;
              res.data.base.buttonList = [];
              res.data.base.tempList = [];
              res.data.base.list = this.$cu.deepClone(res.data.list);
              this.btnPermissions.forEach((v, ind) => {
                res.data.list.forEach(item => {
                  if (v.buttonId === item.buttonId) {
                    res.data.base.buttonList.push(ind)
                    res.data.base.tempList.push(ind)
                  }
                })
              });
              this.form = res.data.base;
              resolve();
            }
          })
        })
      },
      // 添加菜单接口
      addMenuApi() {
        return new Promise(resolve => {
          addMenu({
            name: this.form.name,
            url: this.form.url,
            pid: this.form.pid ? this.form.pid : null,
            filePath: this.form.resourceType === 2 ? this.form.filePath : '',
            icon: this.form.icon,
            seq: this.form.seq,
            resourceType: this.form.resourceType,
            type: 6
          }).then(res => {
            if (res.code === 1) {
              if (this.form.resourceType === 2) {
                this.addBtnPermissionsApi(res.data).then(() => {
                  this.onSuccess('添加成功!');
                })
              } else this.onSuccess('添加成功!');
              resolve();
            } else this.loading = false
          })
        })
      },
      // 编辑菜单接口
      modifyMenuApi() {
        return new Promise(resolve => {
          modifyMenu({
            id: this.form.id,
            name: this.form.name,
            url: this.form.url,
            pid: this.form.pid ? this.form.pid : null,
            filePath: this.form.resourceType === 2 ? this.form.filePath : '',
            icon: this.form.icon,
            seq: this.form.seq,
            resourceType: this.form.resourceType,
            type: 6
          }).then(res => {
            if (res.code === 1) {
              if (this.form.resourceType === 2) {
                this.addBtnPermissionsApi({}).then(() => {
                  this.onSuccess('编辑成功!');
                })
              } else this.onSuccess('编辑成功!');
              resolve();
            } else this.loading = false
          })
        })
      },
      // 新增按钮权限
      addBtnPermissionsApi({id}) {
        return new Promise(resolve => {
          addBtnPermissions({
            name: this.form.name,
            url: this.form.url,
            pid: id ? id : this.form.id,
            filePath: this.form.filePath,
            icon: this.form.icon,
            seq: this.form.seq,
            resourceType: 3,
            buttonLists: JSON.stringify(this.buttonLists),
            deleteButtonList: JSON.stringify(this.deleteButtonList)
          }).then(res => {
            console.log(res);
            if (res.code === 1) {
              if (this.form.name === '菜单管理') {
                let form = this.$cu.deepClone(this.form)
                form.buttonList = this.buttonList;
                this.$cu.vuex('vuex_menu', form);
              }
              resolve();
            } else this.loading = false
          })
        })
      }
    }
  }
</script>

<style scoped lang="less">
  .node-key {
    display: flex;
    flex-wrap: wrap;
    height: 310px;
    overflow: auto;
    justify-content: space-around;

    &-icon {
      margin: 2px;
    }

    &-icon:hover {

    }
  }
  /*.node-key::-webkit-scrollbar{
    display:none;
  }*/
</style>
